﻿
using System ;

using MskEdit.Sdk ;


namespace MskEdit.Dxf.Model
{

    public class DxfTable
    {
        private string[]    allLines_ ;
        private SdkSubrange subrange_ ;
        
        private string  handle_ ;
        private string  ownerPointer_ ;
        private string  subclassMarker_ ;
        private short?  maxEntries_ ;


        public static DxfTable TryFrom( string[] allLines, ref int lineNo, DxfTable fallbackValue ) {
            
            if ( allLines.Length <= lineNo + 1 ) 
                return fallbackValue ;
        
            int internalLineNo = lineNo + 2 ;
                
            if ( ! "TABLE".Equals( allLines[internalLineNo - 1] ) )
                return fallbackValue ;
            
            bool endtabFound = false ;
            
            for ( ; internalLineNo < allLines.Length; ++internalLineNo ) {
                endtabFound = "ENDTAB".Equals( allLines[internalLineNo] ) ;
                if ( endtabFound )
                    break ;
            }
            
            if ( ! endtabFound )
                throw new SdkException( "ENDTAB not found in dxf lines." ) ;
            
            SdkSubrange subrange = new SdkSubrange( lineNo, internalLineNo - lineNo + 1 ) ;
                
            lineNo = subrange.End ;
            
            return new DxfTable( allLines, subrange ) ;
        }


        public DxfTable( string[] allLines, SdkSubrange subrange )
        {
            allLines_ = allLines ;
            subrange_ = subrange ;
            
            handle_             = "" ;
            ownerPointer_       = "" ;
            subclassMarker_     = "" ;
            maxEntries_         = null ;
        }


        public override String ToString() {
            return 
                TableName + " " +
                handle_ + " " +
                ownerPointer_ + " " +
                subclassMarker_ + " " +
                maxEntries_.ToString() + " " ; 
        }


        public string TableName {
            get { return allLines_[ subrange_.Begin + 3 ] ; }
        }


        public string Handle {
            get { return handle_ ; }
            set { handle_ = value ; }
        }


        public string OwnerPointer {
            get { return ownerPointer_ ; }
            set { ownerPointer_ = value ; }
        }


        public string SubclassMarker {
            get { return subclassMarker_ ; }
            set { subclassMarker_ = value ; }
        }


        public short? MaxEntries {
            get { return maxEntries_ ; }
            set { maxEntries_ = value ; }
        }

    }
}
